/* 
  详情页操作 
  1. 获取商品id
  2. 根据id调用商品详情接口获取商品详情数据
  3. 渲染数据到页面 
*/
/*
 *1. 获取商品id
 */
function getProductId() {
    //http://127.0.0.1:5500/code/detail.html?id=4055442
    let url = location.href
    let params = url.substring(url.indexOf('?') + 1)
    let arr = params.split('=')
    let id = arr[1]
    return id
}

/**
 * 2. 根据id调用商品详情接口获取商品详情数据
 */
let product = {} //保存商品详情
function getProductDetail() {
    let id = getProductId()
    $.ajax({
        url: 'http://www.xiongmaoyouxuan.com/api/detail',
        type: 'get',
        data: {
            id
        },
        success: function (res) {
            showProductDetail(res.data)

            product = {
                id: res.data.detail.id,
                name: res.data.share.title,
                url: res.data.share.imageUrl,
                price: res.data.detail.price
            }
        }
    })
}

/* 
3. 渲染数据到页面 
*/
function showProductDetail(data) {
    let str = `
        <div class="g-left">
            <div class="m-show">
                <img src="${data.share.imageUrl}" alt="">
                <div class="mask"></div>
            </div>
            <ul class="m-choose">
                <li class="active"><img src="${data.detail.photo[0].url}" width="60px" alt="1"></li>
                <li><img src="${data.detail.photo[1].url}" width="60px" alt="2"></li>
                <li><img src="${data.detail.photo[2].url}" width="60px" alt="3"></li>
                <li><img src="${data.detail.photo[3].url}" width="60px" alt="4"></li>
            </ul>
        </div>

        <div class="glass">
        <img src="${data.detail.photo[0].url}">
         </div>

        
 <div class="g-container">
 <p>${data.shop.platformName}</p>
        <h2>${data.share.title}</h2>
        <div class="content-font">
        <span class="originPrice">原价￥${data.detail.originPrice}</span>
        <span class="price">券后价：￥${data.detail.price}</span>
        <span class="couponValue">${data.detail.couponValue}</span>
        <span class="goodRatePercentage">${data.shop.goodRatePercentage}人已买</span>
        </div>
        <div class="g-container-button">
        <button class="cart-add" onclick="onAddCart()">加入购物车</button>
        <button class="cart-look" onclick="onLookcart()">查看购物车</button>
        </div>
    </div>
             <div class="glass-right">
                 <p>卖家信息</p>
                 <img src="${data.detail.shop.jumpUrl}">
                 <h2>${data.detail.shop.nickname}</h2>
                 <p>${data.detail.shop.shopScoreText}</p>
        
             </div>

        
        <div class="detail">
            <div class="imgs">
                    <img src="${data.detail.photo[1].url}" alt="">
                    <img src="${data.detail.photo[1].url}" alt="">
                    <img src="${data.detail.photo[1].url}" alt="">
                    <img src="${data.detail.photo[1].url}" alt="">
                    <img src="${data.detail.photo[1].url}" alt="">
                </div>
            </div>

    `
    $('.wraper').html(str)

    onTab()
    onGlass()
}

function getIndex() {
    $('.Index').click(function() {
        location.href = "../pages/index.html"
    })
    
}
getIndex()

/* tab切换 */
function onTab() {
    $('.m-choose>li').mouseover(function () {
        let index = $(this).index() //序号
        //清除所有active
        $('.m-choose>li').removeClass('active')
        //设置选中效果
        $(this).addClass('active')

        // $(this).addClass('active').siblings().removeClass('active')
        //更换图片
        let url = $(this).find('img').prop('src')
        $('.m-show').find('img').prop('src', url)

        $('.glass>img').prop('src', url)

    })
}
/* 放大镜 */
function onGlass() {
    $('.m-show').mouseover(function () {
        $('.mask').css('display', 'block')
        $('.glass').css('display', 'block')
    })

    $('.m-show').mouseout(function () {
        $('.mask').css('display', 'none')
        $('.glass').css('display', 'none')
    })

    //计算放大镜背景图片比例
    let bgW = $('.glass').width() * $('.m-show').width() / $('.mask').width()
    let bgH = $('.glass').height() * $('.m-show').height() / $('.mask').height()
    $('.glass>img').css({
        width: bgW,
        height: bgH
    })

    //移动事件
    $('.m-show').mousemove(function (e) {
        e = e || window.event
        let x = e.offsetX - $('.mask').width() / 2
        let y = e.offsetY - $('.mask').height() / 2

        //边界检查
        if (x < 0) x = 0
        if (x > $('.m-show').width() - $('.mask').width()) {
            x = $('.m-show').width() - $('.mask').width()
        }

        if (y < 0) y = 0
        if (y > $('.m-show').height() - $('.mask').height()) {
            y = $('.m-show').height() - $('.mask').height()
        }

        $('.mask').css({
            top: y,
            left: x
        })

        //计算大图移动比例
        let moveX = x * $('.glass').width() / $('.mask').width()
        let moveY = y * $('.glass').height() / $('.mask').height()
        $('.glass>img').css({
            top: -moveY,
            left: -moveX
        })
    })

}

//入口
getProductDetail()

// 回到顶部
let topEle = document.querySelector(".return-top")
topEle.onclick = function () {
    //alert(11);
    timer = setInterval(function () {
        var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        var ispeed = Math.floor(-scrollTop / 1);
        if (scrollTop == 0) {
            clearInterval(timer);
        }
        document.documentElement.scrollTop = document.body.scrollTop = scrollTop + ispeed;
    }, 30)

};

/* 
  加入购物车 
   构造商品对象，保存到localstorage数组
      => 确定商品对象属性
          {序号	商品图片	商品信息	单价	数量}
        如何获取 序号	商品图片	商品信息    ?
*/
function onAddCart() {
    //判断当前商品是否已经存储在localstorage中
    //如果存在，改变数量
    //不存在，生成新商品加入
    let cartArrayStr = localStorage.getItem('CARTLIST')
    let cartArray = JSON.parse(cartArrayStr) || []
    let oldProduct = cartArray.find(item => item.id == product.id)
    if (oldProduct) {
        oldProduct.num++
        oldProduct.singlePrice = (oldProduct.price * oldProduct.num).toFixed(2) //商品价格*数量
    } else {
        let newProduct = {
            ...product,
            num: 1,
            singlePrice: 0,
            state: false
        }
        cartArray.push(newProduct)
        newProduct.singlePrice = (newProduct.price * newProduct.num).toFixed(2) //商品价格*数量
    }

    localStorage.setItem('CARTLIST', JSON.stringify(cartArray))

    alert('加入购物车成功!')

}

//查看购物车跳转
function onLookcart() {
    location.href = "../pages/goodscart.html"
}